package org.madgecko.basic.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.output.FileWriterWithEncoding;

public class FreeMarkerUtil {
	private static FreeMarkerUtil util;
	private static Configuration cfg;
	
	public static FreeMarkerUtil getInstance(String ftlPath){
		if(null==util){
			cfg = new Configuration();
			cfg.setClassForTemplateLoading(FreeMarkerUtil.class, ftlPath);
			cfg.setDefaultEncoding("utf-8");
			util = new FreeMarkerUtil();
		}
		return util;
	}
	
	private Template getTemplate(String tmpName){
		try {
			return cfg.getTemplate(tmpName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void sPrint(Map<String, Object> root, String tmpName){
		try {
			getTemplate(tmpName).process(root, new PrintWriter(System.out));
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void fPrint(Map<String, Object> root, String tmpName, String outpath){
		try {
			Template template = getTemplate(tmpName);
			template.setEncoding("utf-8");
			template.process(root, new FileWriterWithEncoding(outpath, "utf-8"));
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
